<template>
	<view class="uni-content" :style="{ paddingTop: top + 'px' }">
		<view class="login-logo">
			<image src="/static/jtlogo.png"></image>
		</view>
		<!-- 顶部文字 -->
		<text class="title title-box">{{ title }}</text>
		<text class="description">{{ description }}</text>
		<u--form
			ref="loginFormRef"
			:model="loginData"
			:rules="loginRules"
			:errorType="errorType"
			labelPosition="left">
			<u-form-item @click="showSystem = true">
				<u--input
					v-model="loginSystemText"
					class="input-box input-select"
					placeholder="请选择登录"
					readonly></u--input>
			</u-form-item>
			<u-form-item prop="memberEmpNo">
				<scan-bar
					v-show="!loginData.memberEmpNo"
					ref="scanBarRef"
					@code-scanned="getScanResult"
					:key="1"
					placeholder="请扫描员工号"></scan-bar>
				<u--input
					v-show="loginData.memberEmpNo"
					v-model="loginData.memberEmpNo"
					password
					disabled
					class="input-box"
					placeholder="请扫描员工号"></u--input>
			</u-form-item>
		</u--form>

		<!-- 工作中心 picker -->
		<u-picker
			:show="showWorkCenter"
			:columns="workCenterList"
			keyName="name"
			immediateChange
			@cancel="showWorkCenter = false"
			@confirm="workCenterSelect"></u-picker>

		<!-- 班组 picker -->
		<u-picker
			:show="showCrew"
			:columns="workCrewList"
			keyName="crewName"
			immediateChange
			@cancel="showCrew = false"
			@confirm="crewSelect"></u-picker>

		<!-- 扫码登录 -->
		<button
			class="uni-btn"
			type="primary"
			@click="pwdLogin"
			:loading="loading">
			登 录
		</button>

		<!-- 忘记密码 -->
		<view class="link-box">
			<view>
				<text class="link" @click="toRetrievePwd">
					忘记密码
					<text style="color: #999"></text>
				</text>
			</view>
		</view>

		<!-- 其他操作 -->
		<view class="tool">
			<view @click="jumpTo('/pages/login/accountLogin')">
				<view class="iconView">
					<u-icon name="account" color="#2979ff" size="35px"></u-icon>
				</view>
				<text>账号</text>
			</view>
			<!-- <view @click="jumpTo('/pages/login/ipLogin')">
				<view class="iconView">
					<u-icon name="setting" color="#2979ff" size="35px"></u-icon>
				</view>
				<text>设置</text>
			</view> -->
		</view>
		<u-action-sheet
			:actions="systemList"
			:title="systemTitle"
			:show="showSystem"
			:closeOnClickOverlay="true"
			:closeOnClickAction="true"
			@select="selectSystem"
			@close="showSystem = false"></u-action-sheet>
	</view>
</template>

<script setup lang="ts">
// 导入仓库
import { useUserStore } from "@/stores/useUserStore";
import { reactive, ref, toRaw, computed, watch } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { produceWorkshopList, produceCrewList } from "@/api/common";
import ScanBar from "@/components/scan-bar/index.vue";

const title = process.env.VITE_APP_TITLE;
const description = process.env.VITE_APP_DES;
const showSystem = ref(false);
const top = uni.getSystemInfoSync().safeAreaInsets.top;
// 登录系统判断
const loginSystemText = computed(
	() =>
		systemList.value.filter(
			(e) => e.value === useUserStore().loginSystemStore
		)[0]?.name
);
const loginSystemValue = computed(
	() =>
		systemList.value.filter(
			(e) => e.value === useUserStore().loginSystemStore
		)[0]?.value
);
const hasCrewLogin = computed(
	() => useUserStore().loginSystemStore === "app:mes"
);

const systemTitle = ref("请选择登录");
const systemList = ref([
	{
		name: "MES生产",
		value: "app:mes",
	},
	{
		name: "WMS物流",
		value: "app:wms",
	},
]);
const scanBarRef = ref();
// 获取扫码结果
function getScanResult(result: any) {
	console.log("扫码结果", result);
	loginData.memberEmpNo = result;
	if (
		loginData.parameters.crewId &&
		loginData.parameters.workCenterId &&
		result
	) {
		pwdLogin();
	}
}
function selectSystem(e) {
	if (e.name !== loginSystemText.value) {
		useUserStore().setLoginSystemStore(e.value);
		showSystem.value = false;
	}
}
onShow(async () => {
	const { data } = await produceWorkshopList({});
	data.forEach((item) => {
		item.name = `${item.workshopCode}-${item.workshopName}`;
	});
	workCenterList[0] = data;

	if (loginData.parameters.workCenterId) {
		const res = await produceCrewList({
			workCenterId: loginData.parameters.workCenterId,
		});
		workCrewList[0] = res.data;
	}
});
// 显示待开发提示
function showTip() {
	uni.showToast({
		title: "敬请期待",
		icon: "none",
	});
}

// 定义基本表单信息
const loginFormRef = ref();
const loginData = reactive({
	// loginName: 'admin',
	// passWord: 'pp%@5njj9@owr~Ia',
	parameters: {
		appMenuId: "", // 登录menu类型，物流，生产
		workCenterId: "", // 工作中心id
		workCenterName: "", // 工作中心名称
		crewId: "", // 班组id
		crewName: "", // 班组name
	},
	memberEmpNo: "", // 员工编号
});

const loginRules = ref({
	"parameters.workCenterName": {
		type: "string",
		required: true,
		message: "请选择工作中心",
		trigger: ["blur", "change"],
	},
	"parameters.crewName": {
		type: "string",
		required: true,
		message: "请选择班组",
		trigger: ["blur", "change"],
	},
});

// 定义其他表单信息
const errorType = ref("toast");

/**
 * 选择工作中心
 */
const showWorkCenter = ref(false);
const workCenterList = reactive([]);
async function workCenterSelect(e) {
	if (e.value.length) {
		loginData.parameters.workCenterId = e.value[0].id;
		loginData.parameters.workCenterName = e.value[0].name;
		const { data } = await produceCrewList({ workCenterId: e.value[0].id });
		workCrewList[0] = data;
		loginData.parameters.crewId = "";
		loginData.parameters.crewName = "";
	} else {
		loginData.parameters.workCenterId = "";
		loginData.parameters.workCenterName = "";
		workCrewList[0] = [];
	}
	showWorkCenter.value = false;
}

/**
 * 选择班组
 */
const showCrew = ref(false);
const workCrewList = reactive([]);
function crewSelect(e) {
	if (e.value.length) {
		loginData.parameters.crewId = e.value[0].id;
		loginData.parameters.crewName = e.value[0].crewName;
		scanBarRef.value.reset();
	} else {
		loginData.parameters.crewId = "";
		loginData.parameters.crewName = "";
	}
	showCrew.value = false;
}
/**
 * 忘记密码
 */
function toRetrievePwd() {
	uni.showToast({
		title: "请联系管理员",
	});
}
/**
 * 组织键盘弹出
 */
function hideKeyboard() {
	showWorkCenter.value = true;
	uni.hideKeyboard();
}
/**
 * 组织键盘弹出
 */
function crewhideKeyboard() {
	showCrew.value = true;
	uni.hideKeyboard();
}
/**
 * 登录
 */ const loading = ref(false);
function pwdLogin() {
	if (!loginSystemText.value) {
		uni.showToast({
			title: "请先选择登录",
			icon: "none",
		});
		return false;
	}
	loginData.parameters.appMenuId = loginSystemValue.value || "";
	loginData.memberEmpNo = scanBarRef.value.scanCode;
	console.log(loginData);
	console.log(loginSystemText.value);

	loading.value = true;
	loginFormRef.value
		.validate()
		.then(async (res) => {
			await useUserStore()
				.login(toRaw(loginData))
				.finally(() => {
					loading.value = false;
					loginData.memberEmpNo = "";
				});
		})
		.catch((errors) => {
			console.log("errors", errors);
			loading.value = false;
		});
}
function openScan() {
	/* #ifdef H5 */
	uni.showToast({
		icon: "none",
		title: "请到安卓设备进行扫码",
	});
	/* #endif */
	// 只允许通过相机扫码
	uni.scanCode({
		scanType: ["barCode", "qrCode", "datamatrix", "pdf417"],
		onlyFromCamera: true,
		success: async (res) => {
			console.log("条码类型：" + res.scanType);
			console.log("条码内容：" + res.result);
			loginData.memberEmpNo = res.result;
			await useUserStore()
				.login(toRaw(loginData))
				.finally(() => (loading.value = false));
		},
		fail: async (err) => {
			if (err.errMsg !== "scanCode:fail cancel") {
				uni.showModal({
					title: "扫描失败",
					content: err.errMsg,
				});
				// 模拟成功
				// loading.value = false;
				// loginData.memberEmpNo = '300001';
				// await useUserStore()
				// 	.login(toRaw(loginData))
				// 	.finally(() => (loading.value = false));
			}
		},
	});
}
/**
 * 跳转
 */
function jumpTo(url) {
	uni.redirectTo({
		url: url,
	});
}
</script>

<style lang="scss" scoped>
@import "@/static/css/login-page.scss";

@media screen and (min-width: 690px) {
	.uni-content {
		height: auto;
	}
}

:deep(.searchScan) {
	width: 100%;
	padding: 0px 6px;
	background-color: #f8f8f8 !important;
	.u-search__content {
		flex-direction: row-reverse;
		padding: 0px;
		height: 44px;
		background-color: #f8f8f8 !important;
		border: none;
		.u-search__content__input {
			background-color: #f8f8f8 !important;
		}
		.u-search__content__input--placeholder {
			color: rgb(192, 196, 204) !important;
			font-family: 15px !important;
		}
	}
}

.forget {
	font-size: 12px;
	color: #8a8f8b;
}

.link-box {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	justify-content: space-between;
	margin-top: 20px;
}

.link {
	font-size: 13px;
}
.tool {
	display: flex;
	width: 100%;
	background: #ffffff;
	justify-content: space-evenly;
	margin-top: 20px;

	> view {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin: 0 20px;

		& text {
			font-size: 15px;
			font-weight: 400;
			color: #999;
			line-height: 32rpx;
		}

		& .iconView {
			width: 60px;
			height: 60px;
			background: #ecf5ff;
			border-radius: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 10px;
		}
	}
}
</style>
